// 检查浏览器支持 SpeechRecognition
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition;
let isVoiceControlEnabled = false;  // 默认状态：语音控制禁用
if(localStorage .getItem('isVoiceControlEnabled') != null || localStorage .getItem('isVoiceControlEnabled') != undefined){
    isVoiceControlEnabled = JSON.parse(localStorage .getItem('isVoiceControlEnabled'));
    console.log('初始化语音控制');
    setTimeout(() => {
        startRecognition();
    }, 1000);
}
const defaultCommands = {
    nextAudio: "下一个;换一个",
    proAudio: "上一个",
    openComments: "看评论;打开评论;评论区;打开评论区",
    like: "点赞",
    notInterested: "不感兴趣",
    viewAuthor: "看作者",
    collect: "收藏",
    share: "分享",
    playPause: "播放;暂停",
    fullScreenWeb: "网页全屏",
    fullScreen: "全屏"
};
let commands = [];
if(localStorage .getItem('commands') == null || localStorage .getItem('commands') == undefined ){
    localStorage .setItem('commands', JSON.stringify(defaultCommands));
    commands = JSON.parse(localStorage .getItem('commands'));
}else{
    commands = JSON.parse(localStorage .getItem('commands'));
}
// 初始化语音识别
if (SpeechRecognition) {
    recognition = new SpeechRecognition();
    console.log('支持语音识别');
    recognition.lang = 'zh-CN';
    recognition.continuous = true; // 持续识别
    recognition.interimResults = false; // 不返回中间结果

    recognition.onresult = (event) => {
        const transcript = event.results[event.results.length - 1][0].transcript.trim();
        console.log('识别结果:', transcript);
        showMessage(`识别结果: ${transcript}`);
        if (matchesCommand("nextAudio", transcript)) {
            nextAudio();
            return;
        }
        if (matchesCommand("proAudio", transcript)) {
            proAudio();
            return;
        }
        if (matchesCommand("openComments", transcript)) {
            keydown("KeyX");
            return;
        }
        if (matchesCommand("like", transcript)) {
            keydown("KeyZ");
            return;
        }
        if (matchesCommand("notInterested", transcript)) {
            keydown("KeyR");
            return;
        }
        if (matchesCommand("viewAuthor", transcript)) {
            keydown("KeyF");
            return;
        }
        if (matchesCommand("collect", transcript)) {
            keydown("KeyC");
            return;
        }
        if (matchesCommand("share", transcript)) {
            keydown("KeyS");
            return;
        }
        if (matchesCommand("playPause", transcript)) {
            const event = new KeyboardEvent("keydown", {
                key: " ", // 按键的字符值，一个空格字符
                code: "Space", // 按键的物理位置
                keyCode: 32, // 按键的数字编码（旧标准）
                bubbles: true, // 事件是否冒泡
                cancelable: true, // 事件是否可以取消
            });
            document.dispatchEvent(event);
            return;
        }
        if (matchesCommand("fullScreenWeb", transcript)) {
            keydown("KeyY");
            return;
        }
        if (matchesCommand("fullScreen", transcript)) {
            keydown("KeyH");
            return;
        }
    };

    recognition.onerror = (event) => {
        console.error('语音识别出错:', event.error);
    };
    recognition.onend = () => {
        console.log('语音识别停止');
        startRecognition();
    };
}
function startRecognition() {
    if (!recognition) return;
    if (!isVoiceControlEnabled) return;
    console.log('启动语音识别');
    recognition.start();
}
function stopRecognition() {
    if (recognition) {
        console.log('停止语音识别');
        recognition.stop();
    }
}
function keydown(key) {
    console.log(key);
    const event = new KeyboardEvent('keydown', {
        code: key,     // 对应的键盘代码
        charCode: 0,      // 字符码，通常为 0
        bubbles: true,    // 事件是否冒泡
        cancelable: true, // 事件是否可以取消
    });
    // 将事件派发到目标元素，通常是 `document`
    document.dispatchEvent(event);
}
function nextAudio() {
    const event = new KeyboardEvent('keydown', {
        key: 'ArrowDown',   // 按键的字符值
        code: 'ArrowDown',  // 按键的物理位置
        keyCode: 40,        // 按键的数字编码（旧标准）
        bubbles: true,      // 事件是否冒泡
        cancelable: true,   // 事件是否可以取消
    });
    document.dispatchEvent(event);
}
function proAudio() {
    const event = new KeyboardEvent('keydown', {
        key: 'ArrowUp',    // 按键的字符值
        code: 'ArrowUp',   // 按键的物理位置
        keyCode: 38,       // 按键的数字编码（旧标准）
        bubbles: true,     // 事件是否冒泡
        cancelable: true,  // 事件是否可以取消
    });
    document.dispatchEvent(event);
}
function matchesCommand(command, transcript) {
    return commands[command].split(";").some(keyword => keyword + "。" === transcript);
}
// 监听来自 popup.js 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.voiceControlEnabled !== undefined) {
        isVoiceControlEnabled = message.voiceControlEnabled;
        localStorage .setItem('isVoiceControlEnabled', isVoiceControlEnabled);
        console.log(`语音控制 ${isVoiceControlEnabled ? '启用' : '禁用'}`);
        if (isVoiceControlEnabled) {
            startRecognition(); // 启动语音识别
        } else {
            stopRecognition(); // 停止语音识别
        }
    }
    if(message.commands != null || message.commands != undefined){
        commands = message.commands;
        localStorage.setItem('commands', JSON.stringify(commands));
    }
    // 返回响应
    sendResponse({ status: 'success' });

    // 确保返回 true，表示响应是异步的
    return true;
});
function showMessage(message) {
    const msgElement = document.getElementById('message');
    
    if (!msgElement) {
        // 如果消息框不存在，则创建它
        createMessagePopup();
    }
    
    msgElement.textContent = message;
    msgElement.classList.add('show');

    // 自动关闭消息框
    setTimeout(() => {
        msgElement.classList.remove('show');
    }, 1000); // 3秒后自动消失
}
function createMessagePopup() {
    const popupHTML = `
        <div id="message" class="message"></div>
        <style>
            .message {
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                padding: 15px;
                background-color: #409eff;
                color: white;
                border-radius: 5px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                font-size: 16px;
                display: none; /* 默认隐藏 */
                z-index: 9999;
            }

            @keyframes fadeIn {
                from {
                    opacity: 0;
                }
                to {
                    opacity: 1;
                }
            }

            .message.show {
                display: block;
                animation: fadeIn 0.5s ease;
            }
        </style>
    `;
    
    // 将HTML和样式注入到页面中
    document.body.insertAdjacentHTML('beforeend', popupHTML);
}